package com.android.phoenix.activity.location;

import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.phoenix.MainApplication;
import com.android.phoenix.R;
import com.android.phoenix.models.SportRecord;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;

public class SportCycleActivity extends Activity {
	private MapView mapView = null;
	private TextView txt_sport_time;
	private TextView txt_sport_distance;
	private TextView txt_sport_calories;
	private TextView txt_sport_speed;
	private TextView txt_sport_heart_rate;
	private TextView txt_sport_pedaling;
	private TextView txt_sport_elevation;
	private TextView txt_sport_slope_away;
	private Button btn_sport_start_and_finish;
	private ImageView title_Imgbtn_left_up;
	private TextView title_txt_center;
	private TextView title_txt_right_up;
	private static final int LOCATION_DATE = 1;

	private BaiduMap baiduMap;
	private LocationClient locationClient;
	private LocationMode locationMode;
	private OverlayOptions overlayOptions;
	private MapStatusUpdate mapStatusUpdate;
	private BitmapDescriptor bitmapDescriptor;
	private boolean isFisrtLocation = true;
	private int getAllPointsDistance = 0;
	private LatLng temStartPoint = null;
	private LatLng temEndPoint = null;
	private double temTwoPointsDistance = 0;
	private List<LatLng> listLatLngs = new ArrayList<LatLng>();
	private List<LatLng> listLatLngsTem = new ArrayList<LatLng>();
	private List<LatLng> listLatLngsTemSave = new ArrayList<LatLng>();
	private Map<String, String> MsgMap = new HashMap<String, String>();
	private static long startTime = 0;
	private static long endTime = 0;

	private String recordID = "";
	private String recordCalorie = "";
	private String recordDate = "";
	private String recordStartTime = "";
	private String recordEndTime = "";
	private String recordDistance = "";

	private SportRecord record;

	private ProgressDialog mypDialog;

	private static boolean flag = true;

	private static LocationUtils utils = new LocationUtils();;

	/**
	 * 记录最大速度，最小速度，平均速度等。。。
	 * 
	 */
	private float maxSpeed = 0;
	private float minSpeed = 100000.0f;
	private List<Float> listSpeeds = new ArrayList<Float>();

	private float maxAltitude = 0;
	private float minAltitude = 1000000.0f;
	private float totalAltitude = 0;
	private float averageAltitude = 0;
	private List<Float> listAltitude = new ArrayList<Float>();

	private int maxHeartRate = 0;
	private int minHeartRate = 1000000;
	private int totalHeartRate = 0;
	private int index = 0;
	private List<Integer> listHeartRate = new ArrayList<Integer>();

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			Map<String, String> map = new HashMap<String, String>();
			switch (msg.what) {
			case LOCATION_DATE:
				map = (Map<String, String>) msg.obj;
				if (map != null) {
					if (Float.valueOf(map.get("PointsDistance")) >= 1000) {
						txt_sport_distance.setText(String.format("%sKM",
								Integer.valueOf(map.get("PointsDistance"))
										/ 1000.0f + ""));
					} else {
						txt_sport_distance.setText(String.format("%sM",
								Float.valueOf(map.get("PointsDistance")) + ""));
					}
					txt_sport_speed.setText(String.format("%sKM/h",
							map.get("speed")));
					txt_sport_time.setText(LocationUtils.countTime(startTime,
							endTime));
					txt_sport_elevation.setText(String.format("%sM",
							map.get("Altitude")));

					txt_sport_pedaling.setText(LocationUtils.countPedaling(
							Float.parseFloat(map.get("PointsDistance")),
							Float.parseFloat(map.get("speed"))));
					txt_sport_calories.setText(LocationUtils
							.countCalories(Float.parseFloat(map
									.get("PointsDistance"))));
					int heart_rate = Integer.parseInt(LocationUtils
							.countHeartRate());
					txt_sport_heart_rate
							.setText(LocationUtils.countHeartRate());
					if (maxHeartRate < heart_rate) {
						maxHeartRate = heart_rate;
					}
					if (minHeartRate > heart_rate) {
						minHeartRate = heart_rate;
					}
					totalHeartRate += heart_rate;

					if (index % 20 == 0) {
						// 处理存储数据
						Toast.makeText(SportCycleActivity.this,
								"第" + index + "次", 1).show();
						listHeartRate.add(totalHeartRate / index);
					}
					MsgMap.clear();
				}

				break;

			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.acti_sport_cycle);
		// 初始化一些控件
		initView();
		// 初始化定位配置
		initLocation();
		// 初始化titleBar
		initTitleBar();

	}

	/**
	 * 
	 * @ClassName: MyBaiduLocationListener
	 * @Description: TODO(定位后回调接口)
	 * @author: MyBaiduLocationListener
	 * @date: 2014-12-26 下午4:10:06
	 */
	private class MyBaiduLocationListener implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			// TODO Auto-generated method stub
			if (location == null || mapView == null)
				return;
			// 设置返回的定位数据
			MyLocationData locData = new MyLocationData.Builder()
					.accuracy(location.getRadius())
					// 此处设置开发者获取到的方向信息，顺时针0-360
					.direction(100).latitude(location.getLatitude())
					.longitude(location.getLongitude()).build();

			// 设置到地图控制器上
			baiduMap.setMyLocationData(locData);
			LatLng ll = new LatLng(location.getLatitude(),
					location.getLongitude());
			if (ll == null) {
				return;
			}
			listLatLngs.add(ll);
			// 前几个点的跳跃性特别大 对计算距离有影响
			if (flag) {
				if (listLatLngs.size() > 9) {
					flag = false;
				}
				return;
			}
			if (listLatLngs.size() > 10 && listLatLngs.size() < 10000) {

				// 计算距离，10秒内没走到一米不算
				temStartPoint = listLatLngs.get(listLatLngs.size() - 2);
				temEndPoint = listLatLngs.get(listLatLngs.size() - 1);
				temTwoPointsDistance = DistanceUtil.getDistance(temStartPoint,
						temEndPoint);
				if (temTwoPointsDistance > 1) {
					getAllPointsDistance += temTwoPointsDistance;
				}
				// 画线 百度要求画点得大于2小于10000 这里每次画两个点
				listLatLngsTem.add(temStartPoint);
				listLatLngsTem.add(temEndPoint);
				if (listLatLngsTem != null) {
					overlayOptions = new PolylineOptions().width(10)
							.color(0xAAFF0000).points(listLatLngsTem);
					baiduMap.addOverlay(overlayOptions);
					listLatLngsTem.clear();
				}

			}
			// ===============数据处理============
			if (maxSpeed < location.getSpeed()) {
				maxSpeed = location.getSpeed();
			}
			if (maxAltitude < location.getAltitude()) {
				maxAltitude = (float) location.getAltitude();
			}
			if (minAltitude > location.getAltitude()) {
				minAltitude = (float) location.getAltitude();
			}
			totalAltitude += location.getAltitude();

			// ===============数据处理============
			// 取到100个点 存一次 在退出时得判断是否还有点可以存储,使用spit时最后一个是空 切记！！！！
			if (listLatLngs.size() % 100 == 0 && listLatLngs.size() > 0) {
				listLatLngsTemSave.addAll(listLatLngs);
				// save(String latitude,String longitude);
				MySaveThread thread = new MySaveThread(recordID,
						listLatLngsTemSave);
				new Thread(thread).start();

			}
			index = listLatLngs.size();
			if (index % 20 == 0) {
				averageAltitude = totalAltitude / index;
				listAltitude.add(averageAltitude);
				listSpeeds.add(location.getSpeed());
			}

			// 海拔高度
			Log.i("wanglei", "海拔高度-->" + String.valueOf(location.getAltitude()));

			DecimalFormat df = new DecimalFormat("0.0");
			MsgMap.put("speed", String.valueOf(df.format(location.getSpeed())));
			MsgMap.put("PointsDistance",
					String.valueOf(df.format(getAllPointsDistance)));
			MsgMap.put("time", location.getTime());
			// 海拔
			MsgMap.put("Altitude", String.valueOf(location.getAltitude()));
			Message msg = Message.obtain();
			msg.obj = MsgMap;
			msg.what = LOCATION_DATE;
			handler.handleMessage(msg);

			if (isFisrtLocation) {
				isFisrtLocation = false;
				// 将中心点移动到定位点处
				mapStatusUpdate = MapStatusUpdateFactory.newLatLng(ll);
				baiduMap.animateMapStatus(mapStatusUpdate);
			}
			endTime = System.currentTimeMillis();
			// 定位成功加载框消失
			// if (mypDialog.isShowing()) {
			// mypDialog.dismiss();
			// }

		}

		public void onReceivePoi(BDLocation location) {
			// TODO Auto-generated method stub
		}
	}

	private void initView() {
		mapView = (MapView) this.findViewById(R.id.bmapView);
		txt_sport_time = (TextView) this.findViewById(R.id.txt_sport_time);
		txt_sport_distance = (TextView) this
				.findViewById(R.id.txt_sport_distance);
		txt_sport_calories = (TextView) this
				.findViewById(R.id.txt_sport_calories);
		txt_sport_speed = (TextView) this.findViewById(R.id.txt_sport_speed);
		txt_sport_heart_rate = (TextView) this
				.findViewById(R.id.txt_sport_heart_rate);
		txt_sport_pedaling = (TextView) this
				.findViewById(R.id.txt_sport_pedaling);
		txt_sport_elevation = (TextView) this
				.findViewById(R.id.txt_sport_elevation);
		txt_sport_slope_away = (TextView) this
				.findViewById(R.id.txt_sport_slope_away);
		btn_sport_start_and_finish = (Button) this
				.findViewById(R.id.btn_sport_start_and_finish);

		mapView.removeViewAt(1);
		baiduMap = mapView.getMap();
		// 深圳22.53676, 113.9693
		// 设置首次进入的中心点武汉 new LatLng(30.494986, 114.546405)
		MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newLatLngZoom(
				new LatLng(22.53676, 113.9693), 15.0f);
		baiduMap.animateMapStatus(mapStatusUpdate);
		// 自定义marker
		bitmapDescriptor = BitmapDescriptorFactory
				.fromResource(R.drawable.icon_geo);

	}

	/**
	 * 
	 * @Title: initLocation
	 * @Description: TODO(初始化地图定位所需要的配置)
	 * @author: 汪雷
	 * @date: 2014-12-26 下午4:04:52
	 */
	private void initLocation() {
		locationMode = LocationMode.FOLLOWING;
		baiduMap.setMyLocationConfigeration(new MyLocationConfiguration(
				locationMode, true, bitmapDescriptor));
		baiduMap.setMyLocationEnabled(true);
		locationClient = new LocationClient(this);
		locationClient.registerLocationListener(new MyBaiduLocationListener());
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);// 打开gps
		option.setCoorType("bd09ll"); // 设置坐标类型
		option.setScanSpan(20000);// 设置定位间隔10秒 亲自己测算 大概是2秒
		option.setIsNeedAddress(true);
		btn_sport_start_and_finish.setOnClickListener(new btnClick(option));
		LocationUtils gps = new LocationUtils();
		if (!gps.isGpsEnable(SportCycleActivity.this)) {
			dialog();
		}

		option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
		option.setLocationNotify(true);
		// 设置定位选项
		locationClient.setLocOption(option);
		// 启动定位
		locationClient.start();
	}

	@Override
	protected void onResume() {
		// 在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
		mapView.onResume();
		super.onResume();
	}

	@Override
	protected void onPause() {
		// 在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
		mapView.onPause();
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		// 关闭定位图层
		baiduMap.setMyLocationEnabled(false);
		mapView.onDestroy();
		mapView = null;
		super.onDestroy();
	}

	/**
	 * 
	 * @Title: dialog
	 * @Description: TODO(设置高精度定位)
	 * @author: wWX230766
	 * @date: 2014-12-29 下午5:22:42
	 * @param option
	 */
	protected void dialog() {
		AlertDialog.Builder builder = new Builder(SportCycleActivity.this);
		builder.setMessage("设置高精度定位（必须开启gps）");
		builder.setTitle("提示");
		builder.setPositiveButton("确认", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int arg1) {
				// TODO Auto-generated method stub
				// 打开设置GPS界面
				Intent intent = new Intent(
						Settings.ACTION_LOCATION_SOURCE_SETTINGS);
				startActivityForResult(intent, 0);
				dialog.dismiss();
			}
		});
		builder.create().show();
	}

	/**
	 * 
	 * @ClassName: btnClick
	 * @Description: TODO(点击开始或者停止定位)
	 * @author: btnClick
	 * @date: 2015-1-6 下午5:27:46
	 */
	private class btnClick implements View.OnClickListener {
		LocationClientOption option;
		boolean isStarting = false;

		public btnClick(LocationClientOption option) {
			this.option = option;
		}

		@Override
		public void onClick(View view) {
			if (isStarting) {
				// 停止定位
				locationClient.stop();
				btn_sport_start_and_finish.setText(R.string.btn_sport_start);
				isStarting = false;

				// 完成运动后，剩余的点也存起来
				if (listLatLngs.size() % 100 != 0) {
					listLatLngsTemSave.addAll(listLatLngs);
					MySaveThread thread = new MySaveThread(recordID,
							listLatLngsTemSave);
					new Thread(thread).start();
				}

				// 设置终止时间
				// recordEndTime = LocationUtils.getEndTime();
				recordEndTime = System.currentTimeMillis() + "";
				record.setEndTime(recordEndTime);
				// 设置卡路里
				recordCalorie = txt_sport_calories.getText().toString()
						.replace("千卡", "");
				record.setCalorie(recordCalorie);
				// 设置运动距离
				recordDistance = getAllPointsDistance / 1000.0f + "";
				record.setDistance(recordDistance);

				// 存取最大速度最小速度等··
				Log.i("wanglei", "speed" + String.valueOf(minSpeed));
				record.setMinSpeed(String.valueOf(minSpeed));
				record.setMinAltitude(String.valueOf(minAltitude));
				record.setMinHeartRate(String.valueOf(minHeartRate));

				record.setMaxAltitude(String.valueOf(maxAltitude));
				record.setMaxSpeed(String.valueOf(maxSpeed));
				record.setMaxHeartRate(String.valueOf(maxHeartRate));

				try {
					MainApplication.getDataHelper(SportCycleActivity.this)
							.getSportRecordDao().createOrUpdate(record);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					Log.i("wanglei", "wanglei--->error");
					Toast.makeText(SportCycleActivity.this, e.toString(),
							Toast.LENGTH_SHORT).show();
				}

				if (listSpeeds.size() > 0 && listAltitude.size() > 0
						&& listHeartRate.size() > 0) {

					StringBuffer sb = new StringBuffer();
					// 15,18,20,22,13;50,22,60,50,45;90,120,130,140,150;
					// 速度，速度，速度，速度；海拔，海拔，海拔，海拔；心率，心率，心率，心率；
					for (int i = 0; i < listSpeeds.size(); i++) {
						sb.append(listSpeeds.get(i));
						sb.append(",");
					}
					sb.append(";");
					for (int j = 0; j < listAltitude.size(); j++) {
						sb.append(listAltitude.get(j));
						sb.append(",");
					}
					sb.append(";");
					for (int k = 0; k < listHeartRate.size(); k++) {
						sb.append(listHeartRate.get(k));
						sb.append(",");
					}
					LocationUtils.saveToFile(recordID + "a", sb.toString());
				}

			} else {
				// 设置仅设备(Gps)模式
				if (utils.isGpsEnable(SportCycleActivity.this)) {
					// option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
					btn_sport_start_and_finish
							.setText(R.string.btn_sport_finish);
					startTime = System.currentTimeMillis();
					isStarting = true;
					// myprogressBar(SportCycleActivity.this);

					record = new SportRecord();
					// 传入ID 格式：20150126111652
					recordID = LocationUtils.getCurrentTime();
					record.setId(recordID);
					// 传入date 格式：2015/01/27
					recordDate = LocationUtils.getCurrentDate();
					record.setDate(recordDate);
					// 传入开始时间 格式：11:22:56
					// recordStartTime = LocationUtils.getStartTime();
					record.setStartTime(startTime + "");
					// noticeDialog();
				} else {
					dialog();
				}
			}

		}
	}

	/**
	 * 
	 * @Title: initTitleBar
	 * @Description: TODO(设置统一的titleBar)
	 * @author: wWX230766
	 * @date: 2015-1-6 下午10:00:48
	 */
	private void initTitleBar() {
		title_Imgbtn_left_up = (ImageView) this
				.findViewById(R.id.title_Imgbtn_left_up);
		title_txt_center = (TextView) this.findViewById(R.id.title_txt_center);
		title_txt_center.setText(R.string.label_sport_cycle);
		title_Imgbtn_left_up.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
		title_txt_right_up = (TextView) this
				.findViewById(R.id.title_txt_right_up);
		title_txt_right_up.setVisibility(View.GONE);
	}

	private void myprogressBar(Context c) {
		mypDialog = new ProgressDialog(c);
		// 实例化
		mypDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		// 设置进度条风格，风格为圆形，旋转的
		mypDialog.setTitle("提示");
		// 设置ProgressDialog 标题
		mypDialog.setMessage("正在精确定位中，请稍等！");
		// 设置ProgressDialog 提示信息
		// mypDialog.setIcon(R.drawable.android);
		// 设置ProgressDialog 标题图标
		// mypDialog.setButton("Google",this);
		// 设置ProgressDialog 的一个Button
		mypDialog.setIndeterminate(false);
		// 设置ProgressDialog 的进度条是否不明确
		mypDialog.setCancelable(true);
		// 设置ProgressDialog 是否可以按退回按键取消
		mypDialog.show();
		// 让ProgressDialog显示
	}

	private class MySaveThread implements Runnable {
		private List<LatLng> mlistLatLngs;
		String dateName = "";
		StringBuilder sb = new StringBuilder();

		public MySaveThread(String dateName, List<LatLng> listLatLngs) {
			this.dateName = dateName;
			mlistLatLngs = listLatLngs;
		}

		@Override
		public void run() {

			for (int j = 0; j < mlistLatLngs.size(); j++) {
				if (j % 5 == 0) {
					sb.append(mlistLatLngs.get(j).latitude);
					sb.append(":");
					sb.append(mlistLatLngs.get(j).longitude);
					sb.append(";");
				}
			}
			LocationUtils.saveToFile(dateName, sb.toString());
			listLatLngsTemSave.clear();
		}

	}

	private void noticeDialog() {
		// TODO Auto-generated method stub
		AlertDialog.Builder builder = new Builder(SportCycleActivity.this);
		builder.setMessage("请在省电管理里确认本应用是否可在后台运行，以免应用再锁屏时停止运行！！");
		builder.setTitle("提示");
		builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int arg1) {
				// TODO Auto-generated method stub
				// 打开设置GPS界面
				dialog.dismiss();
			}
		});
		builder.create().show();
	}

}
